using vue0701.Application.Common.interfaces;

using vue0701.Domain.Entities.App;

using vue0701.Domain.Reposoitiories;

namespace vue0701.Application.Services;

public class UserService
{
    private readonly IRepository<AppUser> _userRepo;
    private readonly IRepository<AppUserRole> _userRoleRepo;
    private readonly IPasswordHasher _passwordHasher;

    public UserService(IRepository<AppUser> userRepo, IRepository<AppUserRole> userRoleRepo, IPasswordHasher passwordHasher)
    {
        _userRepo = userRepo;
        _userRoleRepo = userRoleRepo;
        _passwordHasher = passwordHasher;
    }

    // 创建用户
    public async Task<AppUser> CreateUserAsync(string userName, string password)
    {
        var users = await _userRepo.GetAllAsync();
        if (users.Any(u => u.UserName == userName))
            throw new Exception("用户名已存在");
        var salt = _passwordHasher.GenerateSalt();
        var hash = _passwordHasher.HashPassword(password, salt);
        var user = new AppUser(userName, hash, salt);
        await _userRepo.CreateAsync(user);
        return user;
    }

    // 修改密码
    public async Task ChangePasswordAsync(Guid userId, string newPassword)
    {
        var user = await _userRepo.GetByIdAsync(userId) ?? throw new Exception("用户不存在");
        var salt = _passwordHasher.GenerateSalt();
        var hash = _passwordHasher.HashPassword(newPassword, salt);
        user.SetPassword(hash, salt);
        await _userRepo.UpdateAsync(user);
    }

    // 分配角色
    public async Task AssignRoleAsync(Guid userId, AppRole role)
    {
        var user = await _userRepo.GetByIdAsync(userId) ?? throw new Exception("用户不存在");
        user.AssignRole(role);
        await _userRepo.UpdateAsync(user);
    }

    // 移除角色
    public async Task RemoveRoleAsync(Guid userId, AppRole role)
    {
        var user = await _userRepo.GetByIdAsync(userId) ?? throw new Exception("用户不存在");
        // 找到对应的用户-角色关联
        var userRole =(await _userRoleRepo.GetAllAsync()).FirstOrDefault(x => x.UserId==userId && x.RoleId==role.Id);
        if (userRole != null)
        {
            await _userRoleRepo.DeleteHardAsync(userRole.Id);
        }
    }

    // 查询用户
    public async Task<AppUser?> GetUserByIdAsync(Guid userId)
    {
        return await _userRepo.GetByIdAsync(userId);
    }

    public async Task<IEnumerable<AppUser>> GetAllUsersAsync()
    {
        return await _userRepo.GetAllAsync();
    }
}
